package ControllerView

import View._
import xml.XML
import java.text.Normalizer
import AndroidProjectFile.ProjectParameters
import com.trolltech.qt.gui.{QWidget, QFileDialog}
import FilesGenerator.UserConfig

/**
 * <h1>Welcome View Controller</h1>
 *
 *
 * @author Dany Morard
 * @version 1.0
 */


class ControllerCreateProjectView extends ControllerView {


  /**
   * Signal0 send when the projet is at the end of the creation
   */
  var endCreationProject = new Signal0()


  /**
   * Window for display the different view to create a new project
   */
  var createProjectWindow = new CreateProjectWindow(this, null)


  /**
   * View to display the main info for creating a project
   */
  var mainInfoView = new MainInfoView(this, createProjectWindow)

  /**
   * View to display the secondary info for creating a project
   */
  var secondaryView = new SecondaryInfoView(this, createProjectWindow)

  /**
   * View to display the path of the program needed
   */
  var importSoftView = new ImportSoftView(this, createProjectWindow)


  /**
   * Inidicate if the UserConfig is already done or not
   */
  var isUserConfigDone = false


  var emptyFields = true

  var iconPath = ""


  /**
   * to know where we are in the different view
   */
  protected var stateView = 0;


  // read the os available
  this.readOSAvailable


  /**
   * Initialize the view
   */
  def initView {

    createProjectWindow.show

    stateView = 0


    println("init view")
    mainInfoView.show
    mainInfoView.container.move(0,mainInfoView.container.y)
    mainInfoView.eraseTextField
    mainInfoView.labelPackageExample.setText("")


    secondaryView.hide
    secondaryView.container.move(0, secondaryView.container.y)
    secondaryView.eraseTextField

    importSoftView.hide
    importSoftView.container.move(0, importSoftView.container.y)
    importSoftView.eraseTextField


    createProjectWindow.android.show
    changeTextButtonNext("Next")





    // select the right background
    if (UserConfig.exists){
      createProjectWindow.setBackgroundWithoutPathSoft

      isUserConfigDone = true
    }else{
      createProjectWindow.setBackgroundWithPathSoft

      isUserConfigDone = false
    }


    enableButtonPrevious(false)

    enableButtonNext(false)
  }





  /**
   * Read the list of the available os and
   * set it in the view
   */
  private def readOSAvailable {

    //  list all system present in xml file
    var osList = List[String]()

    val file = XML.loadFile("files/permissions.xml")

    val versions = file \\ "versions" \\ "version"


    for (version <- versions) {
      osList = osList :+ version \\ "@name" + " - " + (version \\ "platform" text)
    }

    osList = osList.reverse

    secondaryView.addVersionOs(osList)

  }


  /**
   * method called when the user click on the cancel button
   */
  def cancelButtonClicked() {

    createProjectWindow.close

  }


  /**
   * method called when the user click on the next button
   */

  def nextButtonClicked() {


    if (createProjectWindow.buttonNext.text == "Finish") {

      // save all data
      secondaryView.saveEntries
      mainInfoView.saveEntries
      importSoftView.saveEntries

      endCreationProject.emit

    }
    else {
      stateView = stateView + 1
      manageView(true)

    }
  }

  /**
   * method called when the user click on the previous button
   */
  def previousButtonClicked() {
    stateView = stateView - 1
    manageView(false)
  }


  /**
   * Manage the sequence of the view
   */
  private def manageView(isNextView: Boolean) = stateView match {

    case -1 =>

      stateView = 0

    case 0 =>



      enableButtonPrevious(false)

      mainInfoView.show

      this.transitionPreviousView(mainInfoView, secondaryView)

       if (isUserConfigDone){

         createProjectWindow.animationViewPoint(583, 102)
       } else {

          createProjectWindow.animationViewPoint(342, 102)
       }


      // set button state
      enableButtonNext(true)

      enableButtonPrevious(false)

      changeTextButtonNext("Next")


    case 1 =>

//      mainInfoView.saveEntries

      enableButtonPrevious(true)

      secondaryView.show

      if (isNextView) {

        secondaryView.saveEntries

        this.transitionNextView(secondaryView, mainInfoView)


         if (isUserConfigDone){

           createProjectWindow.animationViewPoint(102, 583)

         } else{

            createProjectWindow.animationViewPoint(102, 342)
         }

      }

      else {

        this.transitionPreviousView(secondaryView, importSoftView)


        createProjectWindow.animationViewPoint(583, 342)
      }

      changeTextButtonNext("Next")


      if (isUserConfigDone) {
        changeTextButtonNext("Finish")
      }


    case 2 =>

      importSoftView.show

      this.transitionNextView(importSoftView, secondaryView)

      createProjectWindow.animationViewPoint(342, 583)

  //    importSoftView.saveEntries

      changeTextButtonNext("Finish")


    case x: Int => println("error with number")
  }


  /**
   * set a valid string format for field
   */

  def checkProjectName() {
    // set a correct String format
    var enteredString = mainInfoView.lineEditNameProject.text()
    // remote space and set to upper case
    enteredString = enteredString.split(" ").map(_.capitalize) mkString ""
    // remove all accent
    enteredString = Normalizer.normalize(enteredString, Normalizer.Form.NFD).replaceAll("[\u0300-\u036F]", "");
    // set String in edit text
    mainInfoView.lineEditNameProject.setText(enteredString)

    //check fields
    checkEmptyField

  }


  def checkActivityName() {
    // set a correct String format
    var enteredString = mainInfoView.lineEditActivityName.text()
    // remote space and set to upper case
    enteredString = enteredString.split(" ").map(_.capitalize) mkString ""
    // remove all accent
    enteredString = Normalizer.normalize(enteredString, Normalizer.Form.NFD).replaceAll("[\u0300-\u036F]", "")
    // set String in edit text
    mainInfoView.lineEditActivityName.setText(enteredString)

    checkEmptyField
  }


  /**
   * purpose and format package name
   */

  def checkPackageName() {

    //set package format
    var enteredString = mainInfoView.lineEditPackage.text()
    // replace space with point
    enteredString = enteredString.split(" ").mkString(".").toLowerCase()
    // remove accent
    enteredString = Normalizer.normalize(enteredString, Normalizer.Form.NFD).replaceAll("[\u0300-\u036F]", "")

    if (enteredString.split('.').length < 3) {
      mainInfoView.labelPackageExample.setText("error: Package must be minimum 3 directories deep")
      mainInfoView.labelPackageExample.setStyleSheet("* { color:red }")
      mainInfoView.labelPackageExample.show
      mainInfoView.lineEditPackage.setStyleSheet("* { color:red }")
    }
    else {
      mainInfoView.labelPackageExample.hide
      mainInfoView.lineEditPackage.setStyleSheet("* { color:black }")
    }


    mainInfoView.lineEditPackage.setText(enteredString)

    checkEmptyField
  }

  def defaultPackageName() {
    if (mainInfoView.lineEditPackage.text().isEmpty) {
      mainInfoView.lineEditPackage.setPlaceholderText("com.org." + mainInfoView.lineEditNameProject.text().toLowerCase)
    }
  }

  /**
   * check to enable or disable next button
   */
  def checkEmptyField(): Unit = stateView match {
    // in first window
    case 0 => if (!(mainInfoView.lineEditNameProject.text.isEmpty || mainInfoView.lineEditPath.text.isEmpty
      || mainInfoView.lineEditActivityName.text.isEmpty || mainInfoView.lineEditPackage.text.isEmpty
      || mainInfoView.labelPackageExample.isVisible)) {
      enableButtonNext(true)
    }
    else
      enableButtonNext(false)

    // second widnow
    case 1 => if (!(secondaryView.lineEditNameApp.text.isEmpty || secondaryView.lineEditVersionApp.text.isEmpty)) {
      enableButtonNext(true)
    }
    else
      enableButtonNext(false)

    case _ => // do nothing...


  }

  /**
   * Enable or disable the button next
   */
  private def enableButtonNext(state: Boolean) {
    createProjectWindow.buttonNext.setEnabled(state)
  }


  /**
   * Enable or disable the button previous
   */
  private def enableButtonPrevious(state: Boolean) {
    createProjectWindow.buttonPrevious.setEnabled(state)
  }


  /**
   * Change the texte of the button next
   */
  private def changeTextButtonNext(name: String) {
    createProjectWindow.buttonNext.setText(name)
  }

  /**
   * open a window to set emplacement of project
   */
  def selectPathFolder() {
    mainInfoView.lineEditPath.setText(QFileDialog.getExistingDirectory(new QWidget, new String("Open Directory")))
  }

  /**
   * open a window to search icon image
   */
  def selectIconPath() {
    iconPath = QFileDialog.getOpenFileName(new QWidget, new String("Select an icon"), new String(""), new QFileDialog.Filter("Images (*.png *.jpg)"))
    if (iconPath.isEmpty) {
      ProjectParameters.iconPath = "icon/myIcon.png"
    }
    else
      secondaryView.lineEditIconPath.setText(iconPath)
  }

  /**
   * get the field value of minimum version and set it in projectParameters
   */
  def getMinimumVersion() {

    // get platform name selected
    val platformSelected = secondaryView.comboxVersionOs.currentText.split(" ").head.toString

    var apiLevel = 0

    val file = XML.loadFile("files/permissions.xml")

    for (elem <- file \\ "versions" \\ "version") {
      if ((elem \\ "@name" text) == platformSelected) {
        apiLevel = (elem \\ "APILevel" text).toInt
      }
    }

    ProjectParameters minVersion = apiLevel

    checkEmptyField
  }

  /**
   * force user to set the software version in float
   */
  def checkVersionName() {
    secondaryView.lineEditVersionApp.setText(secondaryView.lineEditVersionApp.text.toFloat.toString)

    checkEmptyField
  }

  def endAnimationSlide() = stateView match {


    case 0 =>
      secondaryView.hide


    case 1 =>
      mainInfoView.hide
      importSoftView.hide


    case 2 =>
      secondaryView.hide
      mainInfoView.hide


    case _ =>
      System.err.println("Error !!!")
  }


  /**
   * Launch the animation to go to the previous View
   */

  private def transitionPreviousView(nextView: View, currentView: View) {
    currentView.animationViewSlide(0, 840)
    nextView.animationViewSlide(nextView.container.x, 0)
  }


  /**
   * Launch the animation to go to the next view
   */
  private def transitionNextView(nextView: View, currentView: View) {
    currentView.animationViewSlide(currentView.container.x, -840)
    nextView.animationViewSlide(840, 0)
  }
}

